import logging
import logging.config
import model

from config import *

logging.config.fileConfig(LOGGING_CONF)
logger = logging.getLogger('dmzwatch.purge')


def discovery_purge():
    
    with model.session_scope() as session:
        hosts = session.query(model.Address).all()
        for host in hosts:
            logger.debug('Checking discoveries of host %s', host.ip)
            discoveries = host.discoveries
            last = max(discoveries, key = lambda disc:disc.date).date
            logger.debug('num of discoveries: %s', len(discoveries))
            logger.debug('last discovery at: %s', last)
            for discovery in discoveries:
                if discovery.date < last:
                    logger.debug('discovery at %s is late', discovery.date)
                    session.delete(discovery)
        
def task_purge():
    with model.session_scope() as session:
        hosts = session.query(model.Address).all()
        for host in hosts:
            logger.debug('Checking tasks of host %s', host.ip)
            complete_tasks = session.query(model.Task).filter_by(addr_id = host.uid)\
                                                        .filter(model.Task.status.in_([ExecStatus.error, ExecStatus.complete]))\
                                                        .all()
            logger.debug('num of completed tasks: %s', len(complete_tasks))                                                    
            if len(complete_tasks) > 1:
                  last = max(complete_tasks, key = lambda task:task.end).end
                  logger.debug('last task at %s', last)
                  for task in complete_tasks:
                    if task.end < last:
                        logger.debug('task at %s is late', task.end)
                        session.delete(task)

if __name__ == "__main__":
    
    discovery_purge()
    task_purge()